package 牛客题霸;


import java.util.Stack;

public class 链表中的节点每k个一组翻转 {

    public ListNode reverseKGroup (ListNode head, int k) {
        if(head == null) {
            return null;
        }
        Stack<ListNode> stack = new Stack<>();
        int count = 0;
        ListNode resultHead = new ListNode(-1);
        ListNode cur = resultHead;
        while (head != null) {
            stack.push(head);
            count++;
            head = head.next;
            if(count == k) {
                // 链表需要反转
                while (!stack.isEmpty()) {
                    cur.next = stack.pop();
                    cur = cur.next;
                }
                count = 0;
            }
        }
        ListNode first = null;
        if(!stack.isEmpty()) {
            ListNode pop = stack.pop();
            pop.next = null;
            first = pop;
            while (!stack.isEmpty()) {
                first = stack.pop();
            }
        }
        cur.next = first;
        return resultHead.next;
    }

    public static void main(String[] args) {
        Math.sqrt(100);
    }

    public static class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }
    }
}
